package com.niit.happynicedays;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

public class HappyNiceDaysActivity extends Activity implements Runnable {
	/** Called when the activity is first created. */

	Thread mThread;
	boolean active = false;
	int mTime = 300;
	float volume;
	String fileName = "config.cfg";

	MediaPlayer mMedia;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.main);

		try {
			FileInputStream fis = openFileInput(fileName);
			volume = (float) fis.read() / 10;
			fis.close();
		} catch (Exception ex) {
			// TODO: handle exception
			try {
				FileOutputStream fos = openFileOutput(fileName,
						Context.MODE_PRIVATE);
				fos.write(5);
				fos.close();
				volume = 5;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		mMedia = MediaPlayer.create(getBaseContext(), R.raw.bgsound);
		mMedia.setVolume(volume, volume);
		mMedia.setLooping(false);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		active = true;
		mTime = 300;
		super.onResume();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub
		if (mThread == null) {
			mThread = new Thread(this);
			mThread.start();
			mMedia.start();
		}
		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while (active && mTime > 0) {
				mTime -= 10;
				mThread.sleep(100);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			startActivity(new Intent(getBaseContext(), mainmenu.class));
			finish();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			active = false;
		}
		return super.onTouchEvent(event);
	}
}